package com.wholesale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.wholesale.datas.WebServiceClient;
import com.wholesale.utils.Constants;

public class OrderUseBalanceLayout extends LinearLayout implements
		OnClickListener {
	private ViewFlipper viewFlipper;
	private Context context;
	private View baseView;
	private Button leftButton;
	private Button rightButton;
	private TextView headView;
	private RelativeLayout loadingLayout;

	private TextView youBalanceView;
	private TextView totalPriceView;
	private EditText useBalanceView;
	private double totalPrice;

	private double balance;
	private double userBalances;
	private String str;

	// 构造函数
	public OrderUseBalanceLayout(Context context,
			final ViewFlipper viewFlipper, double totalPrice, double balance) {
		super(context);
		this.viewFlipper = viewFlipper;
		this.context = context;
		this.totalPrice = totalPrice;
		this.balance = balance;
		// 加载需要的属性，加载方法一的子Layout
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(
				R.layout.orderusebalance, this);
		leftButton = (Button) baseView.findViewById(R.id.leftBtn);
		leftButton.setText("Back");
		leftButton.setOnClickListener(this);
		rightButton = (Button) baseView.findViewById(R.id.rightBtn);
		rightButton.setText("OK");
		rightButton.setOnClickListener(this);
		headView = (TextView) baseView.findViewById(R.id.title);
		headView.setText("");
		youBalanceView = (TextView) baseView.findViewById(R.id.balance_text);
		totalPriceView = (TextView) baseView.findViewById(R.id.totalprice_text);
		useBalanceView = (EditText) baseView.findViewById(R.id.usebalance_text);
		str = useBalanceView.getText().toString();
		loadingLayout = (RelativeLayout) baseView
				.findViewById(R.id.loadingLayout);
		if (balance > 0) {
			useBalanceView.setText("" + balance);
		}
		UserBalanceAsync userBalanceAsync = new UserBalanceAsync(context);
		userBalanceAsync.execute((Void) null);
	}

	class UserBalanceAsync extends AsyncTask<Void, Integer, Double> {
		ProgressDialog pdialog;

		public UserBalanceAsync(Context context) {
		}

		@Override
		protected void onPreExecute() {
			loadingLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected Double doInBackground(Void... params) {
			return WebServiceClient.getUserBalance(
					Constants.loginResponse.getUserId(),
					Constants.loginResponse.getUserToken());
		}

		@Override
		protected void onPostExecute(Double result) {
			userBalances = result;
			youBalanceView.setText(Constants.getTwoDecimal(result) + " $");
			totalPriceView.setText(Constants.getTwoDecimal(totalPrice) + " $");
			loadingLayout.setVisibility(View.GONE);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			loadingLayout.setVisibility(View.GONE);
		}
	}

	public void dialog(String title, final String message) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) ((Activity) getContext())
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		switch (v.getId()) {
		case R.id.leftBtn:
			imm.hideSoftInputFromWindow(leftButton.getWindowToken(), 0);
			viewFlipper.showPrevious();
			viewFlipper.removeView(this);
			break;
		case R.id.rightBtn:
			imm.hideSoftInputFromWindow(rightButton.getWindowToken(), 0);
			if (!useBalanceView.getText().toString().equals("")) {
				double value = Double.parseDouble(useBalanceView.getText()
						.toString());
				if (value <= 0 || value > userBalances || value > totalPrice) {
					dialog("Sorry", "Insufficient balance!");
				} else {
					int count = viewFlipper.getChildCount();
					View preView = viewFlipper.getChildAt(count - 2);
					if (preView.getClass().getName()
							.equals(CheckOutLayout.class.getName())) {
						((CheckOutLayout) preView).setUseBalance(value);
					}
					viewFlipper.showPrevious();
					viewFlipper.removeView(this);
				}
			} else {
				dialog("Sorry", "Balance should be number!");
			}
			break;
		default:
			break;
		}

	}
}
